﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace ProductSystem.BLL.Common
{
    public class ExcelResult : ActionResult
    {
        public ExcelResult(string fileName, byte[] bytes)
        {
            this.fileName = fileName;
            this.bytes = bytes;
        }
        public string fileName { get; set; }
        public byte[] bytes { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            if (null == bytes)
            {
                return;
            }
            context.HttpContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); //解决中文乱码
            //解决火狐乱码问题
            if (HttpContext.Current.Request.ServerVariables["http_user_agent"].ToLower().IndexOf("firefox") == -1)
            {
                fileName = System.Web.HttpUtility.UrlEncode(this.fileName, System.Text.Encoding.UTF8);
            }
            context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + this.fileName + ".xls"); //解决中文文件名乱码    
            context.HttpContext.Response.AddHeader("content-length", bytes.Length.ToString());
            context.HttpContext.Response.ContentType = "appliction/octet-stream";
            context.HttpContext.Response.BinaryWrite(bytes);
            context.HttpContext.Response.End();
        }
    }

    public class ImageResult : ActionResult
    {
        public ImageResult(string fileName, byte[] bytes)
        {
            this.fileName = fileName;
            this.bytes = bytes;
        }
        public string fileName { get; set; }
        public byte[] bytes { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            if (null == bytes)
            {
                return;
            }
            context.HttpContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); //解决中文乱码
            //解决火狐乱码问题
            if (HttpContext.Current.Request.ServerVariables["http_user_agent"].ToLower().IndexOf("firefox") == -1)
            {
                fileName = System.Web.HttpUtility.UrlEncode(this.fileName, System.Text.Encoding.UTF8);
            }
            context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + this.fileName + ".png"); //解决中文文件名乱码    
            context.HttpContext.Response.AddHeader("content-length", bytes.Length.ToString());
            context.HttpContext.Response.ContentType = "appliction/octet-stream";
            context.HttpContext.Response.BinaryWrite(bytes);
            context.HttpContext.Response.End();
        }
    }
}
